package com.jdone.compus.controller;

import com.jdone.compus.dto.ApiResponse;
import com.jdone.compus.enums.ConsumptionStatus;
import com.jdone.compus.model.StudentOrder;
import com.jdone.compus.service.StudentOrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.Optional;

/**
 * 学生订单管理控制器。
 */
@RestController
@RequestMapping("/orders")
@Api(value = "学生订单", tags = "学生订单管理")
public class StudentOrderController {

    @Autowired
    private StudentOrderService service;

    /**
     * 创建新的学生订单。
     *
     * @param order 订单信息
     * @return 包含ApiResponse的ResponseEntity
     */
    @PostMapping
    @ApiOperation(value = "创建新的学生订单")
    public ResponseEntity<ApiResponse> createOrder(@RequestBody StudentOrder order) {
        order.setOrderAmount(order.getOrderAmount());
        StudentOrder createdOrder = service.createOrder(order);
        ApiResponse response = new ApiResponse(true, "订单创建成功", createdOrder);
        return ResponseEntity.ok(response);
    }

    /**
     * 根据订单ID获取订单详情。
     *
     * @param id 订单ID
     * @return 包含ApiResponse的ResponseEntity
     */
    @GetMapping("/{id}")
    @ApiOperation(value = "根据订单ID获取订单详情")
    public ResponseEntity<ApiResponse> getOrderById(@PathVariable Long id) {
        Optional<StudentOrder> order = service.getOrderById(id);
        if (order.isPresent()) {
            ApiResponse response = new ApiResponse(true, "订单获取成功", order.get());
            return ResponseEntity.ok(response);
        } else {
            ApiResponse response = new ApiResponse(false, "订单未找到");
            return ResponseEntity.status(404).body(response);
        }
    }

    /**
     * 根据业务订单号获取订单详情。
     *
     * @param businessOrderNo 业务订单号
     * @return 包含ApiResponse的ResponseEntity
     */
    @GetMapping("/business/{businessOrderNo}")
    @ApiOperation(value = "根据业务订单号获取订单详情")
    public ResponseEntity<ApiResponse> getOrderByBusinessOrderNo(@PathVariable String businessOrderNo) {
        Optional<StudentOrder> order = service.getOrderByBusinessOrderNo(businessOrderNo);
        if (order.isPresent()) {
            ApiResponse response = new ApiResponse(true, "订单获取成功", order.get());
            return ResponseEntity.ok(response);
        } else {
            ApiResponse response = new ApiResponse(false, "订单未找到");
            return ResponseEntity.status(404).body(response);
        }
    }

    /**
     * 根据学生ID和时间范围分页获取订单。
     *
     * @param studentId 学生ID
     * @param startDate 开始日期（可选）
     * @param endDate 结束日期（可选）
     * @param page 页码，从0开始
     * @param size 每页显示的记录数
     * @return 包含ApiResponse的ResponseEntity，其中包含订单分页结果
     */
    @GetMapping("/student/{studentId}")
    @ApiOperation(value = "根据学生ID和时间范围分页获取订单")
    public ResponseEntity<ApiResponse> getOrdersByStudentId(
            @PathVariable String studentId,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {

        Pageable pageable = PageRequest.of(page - 1, size);
        Page<StudentOrder> ordersPage = service.getOrdersByStudentIdAndDateRange(studentId, startDate, endDate, pageable);

        ApiResponse response = new ApiResponse(true, "订单获取成功", ordersPage);
        return ResponseEntity.ok(response);
    }

    /**
     * 根据订单ID更新订单的消费状态。
     *
     * @param id     订单ID
     * @param status 新的消费状态
     * @return 包含ApiResponse的ResponseEntity
     */
    @PutMapping("/{id}/status")
    @ApiOperation(value = "根据订单ID更新订单的消费状态")
    public ResponseEntity<ApiResponse> updateOrderStatus(@PathVariable Long id, @RequestParam ConsumptionStatus status) {
        try {
            StudentOrder updatedOrder = service.updateOrderStatus(id, status);
            ApiResponse response = new ApiResponse(true, "订单状态更新成功", updatedOrder);
            return ResponseEntity.ok(response);
        } catch (RuntimeException e) {
            ApiResponse response = new ApiResponse(false, "订单未找到");
            return ResponseEntity.status(404).body(response);
        }
    }

    /**
     * 根据订单ID删除订单。
     *
     * @param id 订单ID
     * @return 包含ApiResponse的ResponseEntity
     */
    @DeleteMapping("/{id}")
    @ApiOperation(value = "根据订单ID删除订单")
    public ResponseEntity<ApiResponse> deleteOrder(@PathVariable Long id) {
        try {
            service.deleteOrder(id);
            ApiResponse response = new ApiResponse(true, "订单删除成功",null);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            ApiResponse response = new ApiResponse(false, "订单未找到");
            return ResponseEntity.status(404).body(response);
        }
    }

    /**
     * 根据订单ID更新订单的其他信息。
     *
     * @param id    订单ID
     * @param order 更新后的订单信息
     * @return 包含ApiResponse的ResponseEntity
     */
    @PutMapping("/{id}")
    @ApiOperation(value = "根据订单ID更新订单的其他信息")
    public ResponseEntity<ApiResponse> updateOrder(@PathVariable Long id, @RequestBody StudentOrder order) {
        try {
            StudentOrder updatedOrder = service.updateOrder(id, order);
            ApiResponse response = new ApiResponse(true, "订单更新成功", updatedOrder);
            return ResponseEntity.ok(response);
        } catch (RuntimeException e) {
            ApiResponse response = new ApiResponse(false, "订单未找到");
            return ResponseEntity.status(404).body(response);
        }
    }


    @ApiOperation(value = "根据时间分页查询")
    @GetMapping("/search")
    public ApiResponse searchOrders(
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate,
            @RequestParam(required = false) ConsumptionStatus consumptionStatus,
            @RequestParam(required = false) String businessOrderNo,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(defaultValue = "1") int pageNum) {

        LocalDateTime startDateTime = startDate != null ? startDate.atStartOfDay() : null;
        LocalDateTime endDateTime = endDate != null ? endDate.plusDays(1).atStartOfDay().minusSeconds(1) : null;

        // 创建 Pageable 对象
        Pageable pageable = PageRequest.of(pageNum - 1, pageSize);

        Page<StudentOrder> orders = service.findOrdersByCreateTime(startDateTime, endDateTime, consumptionStatus, businessOrderNo, pageable);
        return new ApiResponse(true, "查询成功", orders);
    }



    /**
     * 获取订单总数和总金额的接口
     *
     * @param startDateTime 查询的起始时间
     * @param endDateTime 查询的结束时间
     * @return 包含订单总数和总金额的 ApiResponse
     */
    @ApiOperation("获取订单总数和总金额")
    @GetMapping("/stats")
    public ApiResponse getOrderStats(
            @RequestParam(value = "startDateTime", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime startDateTime,
            @RequestParam(value = "endDateTime", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime endDateTime) {

        Map<String, Object> stats = service.getOrderStats(startDateTime, endDateTime);
        return new ApiResponse(true, "统计数据获取成功", stats);
    }

    /**
     * 导出所有订单记录为 Excel 文件的接口
     *
     * @return 包含 Excel 文件的 ResponseEntity
     */
    @ApiOperation("导出所有订单记录为Excel")
    @GetMapping("/export/all")
    public ResponseEntity<byte[]> exportAllOrdersToExcel() {
        try {
            ByteArrayInputStream in = service.exportAllOrdersToExcel();
            ByteArrayOutputStream out = new ByteArrayOutputStream();

            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }

            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Disposition", "attachment; filename=学生订单.xlsx");

            return ResponseEntity.ok()
                    .headers(headers)
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .body(out.toByteArray());
        } catch (IOException e) {
            return ResponseEntity.status(500).body(null);
        }
    }
}
